import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

// 样品接口定义
interface Sample {
  id?: string
  projectId: string
  sampleName: string
  sampleCode?: string
  sampleType?: string
  description?: string
  quantity: number
  unit: string
  status: string
  location?: string
  receivedDate?: string
  testDate?: string
  completedDate?: string
  testResults?: string
  images?: string[]
  notes?: string
  createdBy: string
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 首先检查项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    // 由于我们没有单独的Sample模型，我们返回项目中的样品信息
    // 这里我们可以模拟一些样品数据，或者从项目的sampleImages等字段中提取
    const mockSamples = [
      {
        id: 'sample-1',
        projectId: (await params).id,
        sampleName: '测试样品A',
        sampleCode: 'TS-A-001',
        sampleType: 'material',
        description: '用于初步测试的样品',
        quantity: 5,
        unit: '个',
        status: 'RECEIVED',
        location: '实验室A-01',
        receivedDate: new Date().toISOString(),
        testDate: null,
        completedDate: null,
        testResults: '',
        images: [],
        notes: '初步测试样品',
        createdBy: 'user-1',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ]

    return NextResponse.json(mockSamples)
  } catch (error) {
    console.error('Error fetching samples:', error)
    return NextResponse.json(
      { error: 'Failed to fetch samples' },
      { status: 500 }
    )
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    const {
      sampleName,
      sampleCode,
      sampleType,
      description,
      quantity,
      unit,
      status,
      location,
      receivedDate,
      testDate,
      completedDate,
      testResults,
      images,
      notes,
      createdBy
    }: Sample = body

    // 验证必填字段
    if (!sampleName || !quantity || !unit || !status || !createdBy) {
      return NextResponse.json(
        { error: 'Missing required fields: sampleName, quantity, unit, status, createdBy' },
        { status: 400 }
      )
    }

    // 创建新样品（这里我们模拟创建，因为没有单独的Sample模型）
    const newSample = {
      id: `sample-${Date.now()}`,
      projectId: (await params).id,
      sampleName,
      sampleCode: sampleCode || '',
      sampleType: sampleType || 'other',
      description: description || '',
      quantity,
      unit,
      status,
      location: location || '',
      receivedDate: receivedDate || null,
      testDate: testDate || null,
      completedDate: completedDate || null,
      testResults: testResults || '',
      images: images || [],
      notes: notes || '',
      createdBy,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    // 更新项目的样品信息
    await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        hasSample: true,
        sampleCount: (project.sampleCount || 0) + quantity,
        updateTime: new Date()
      }
    })

    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: (await params).id,
        action: 'SAMPLE_CREATED',
        description: `创建样品: ${sampleName}, 数量: ${quantity}${unit}`,
        userId: createdBy,
        fromLevel1: project.level1,
        fromLevel2: project.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })

    return NextResponse.json(newSample)
  } catch (error) {
    console.error('Error creating sample:', error)
    return NextResponse.json(
      { error: 'Failed to create sample' },
      { status: 500 }
    )
  }
}

// PATCH方法用于更新项目级别的样品信息
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    const { 
      hasSample, 
      sampleCount, 
      sampleImages, 
      updatedBy 
    } = body
    
    const existingProject = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }
    
    const updateData: any = {
      updatedBy,
      updateTime: new Date()
    }
    
    if (hasSample !== undefined) updateData.hasSample = hasSample
    if (sampleCount !== undefined) updateData.sampleCount = sampleCount
    if (sampleImages !== undefined) updateData.sampleImages = sampleImages
    
    const project = await db.researchProject.update({
      where: { id: (await params).id },
      data: updateData,
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: project.id,
        action: 'SAMPLE_UPDATED',
        description: `更新样品信息: ${hasSample ? '有样品' : '无样品'}, 数量: ${sampleCount || 0}`,
        userId: updatedBy,
        fromLevel1: existingProject.level1,
        fromLevel2: existingProject.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error updating project samples:', error)
    return NextResponse.json(
      { error: 'Failed to update project samples' },
      { status: 500 }
    )
  }
}